import { computed, ref, nextTick, onDeactivated, onUnmounted, watch } from 'vue'
import { useStore } from 'vuex'
import { useRouter } from 'vue-router'
import { useMapGetters } from '@/hook/use-map'
import { getMusicLyric } from '@/service/now-music'
import { analyzeLyrics } from '@/utils/analyze-Iyrics'
import SingComment from '@/base-ui/comment'
import MusicSimi from '../cpns/music-simi.vue'
import { Message } from '@/utils/message'

export function InitDoing() {
  const router = useRouter()
  const store = useStore()
  const commentRef = ref<InstanceType<typeof SingComment>>()
  const simiRef = ref<InstanceType<typeof MusicSimi>>()
  if (store.state.music.musicId === 0) {
    router.back()
  }
  const songId = computed(() => {
    nextTick(() => {
      lyricScroll.value!.scrollTop = 0
      lyricIndex.value = 0
      getLyric(store.state.music.musicId)
      commentRef.value?.getSingelComment(songId.value, 0, 30) // 歌曲评论
      simiRef.value?.getSimi(songId.value) //相似歌曲
    })
    return store.state.music.musicId
  })
  // 从vuex获取数据 当前音乐详情以及播放地址
  const gettersMusic = useMapGetters('music', [
    'getMusicDetail',
    'getNowMusic',
    'getIsPlay'
  ])
  // 总容器div ref
  const scroll = ref<InstanceType<typeof HTMLElement>>()
  // 唱片disc 唱片杆bar
  const playBar = ref<InstanceType<typeof HTMLElement>>()
  const playDisc = ref<InstanceType<typeof HTMLElement>>()
  // 歌词滚动
  const lyricScroll = ref<InstanceType<typeof HTMLElement>>()
  const lyric = ref<InstanceType<typeof HTMLElement>>()
  const lyricRef = ref<InstanceType<typeof HTMLElement>>()
  const lrcObject: any = ref([])
  const lyricIndex = ref(0)
  const lyrics = ref('')
  // 返回
  //收缩页面
  const comBack = () => {
    router.back()
  }
  // 获取歌词
  // getLyric(songId.value)
  function getLyric(id: number) {
    getMusicLyric(id).then((res: any) => {
      lyrics.value = res.lrc.lyric
      lrcObject.value = analyzeLyrics(lyrics.value)
    })
  }
  //唱片旋转
  const routeNum = ref(0)
  function routeDeg() {
    playDisc.value!.style.transform = 'rotateZ(' + routeNum.value + 'deg)'
    routeNum.value += 4
  }
  let timeId = 0

  const isPlay = computed(() => {
    const isP = store.state.music.isPlay
    nextTick(() => {
      if (isP) {
        timeId = setInterval(routeDeg, 100)
        playBar.value!.style.transform = 'rotate(0deg)'
      } else {
        clearInterval(timeId)
        playBar.value!.style.transform = 'rotate(-30deg)'
      }
    })
    return store.state.music.isPlay
  })
  const duration = computed(() => {
    return store.state.music.duration
  })
  const stop = watch(
    duration,
    () => {
      const dt = store.state.music.duration
      nextTick(() => {
        //对每次进来的进度条进行判断
        // 跟下一句台词时长是否匹配,如果匹配则当前高亮的索引值+1
        //使用循环找到最接近当前播放时间的歌词
        for (let i = 0; i < lrcObject.value.length; i++) {
          //这里使用小于符号判断是为了 保证回退音乐进度事件的效果实现性
          if (dt <= Number(lrcObject.value[i].t).toFixed(0)) {
            if (lyricIndex.value === i - 1) {
              break
            }
            //找到比当前时间点 大一点的后一位的歌词的索引值
            lyricIndex.value = i - 1
            //动态绑定ref 根据距离顶部不同的位置来控制歌词滚动 (原生的滚动条动画效果未实现，需要的话可能需要换其他滚动条，eg:bater-scroll)
            //这里加入了一个效果就是滑下去查看歌词时，不会自动滑动 只有到了高亮显示在可视区才会滚动
            // 175 是可视区的一半 55是出现离可视区距离 相当于一行高度 都可微调
            if (
              lyricRef.value &&
              lyricScroll.value!.scrollTop + 55 > lyricRef.value!.offsetTop
            ) {
              console.log('不自动滑动')
            } else {
              if (
                lyricRef.value &&
                lyricScroll.value!.scrollTop + 350 > lyricRef.value!.offsetTop
              ) {
                lyricScroll.value!.scrollTop = lyricRef.value!.offsetTop - 135
              }
            }
            //如果当前是最后一句歌词 代表歌曲要放送结束了 将我们的lyricIndex(当前歌词索引值还原成0便于下一曲使用)
            break
          } else if (
            lyricIndex.value === lrcObject.value.length - 2 &&
            dt >=
              Number(lrcObject.value[lrcObject.value.length - 1].t).toFixed(0)
          ) {
            lyricIndex.value = lrcObject.value.length - 1
            break
          } else if (lyricIndex.value === lrcObject.value.length - 1) {
            break
          }
        }
      })
    },
    { immediate: true }
  )

  onDeactivated(() => {
    clearInterval(timeId)
    // stop()
  })
  onUnmounted(() => {
    clearInterval(timeId)
    stop()
  })
  // 返回顶部
  function handleTop() {
    scroll.value!.scrollTop = 0
  }

  // 收藏
  const likeFlag = ref(false)
  const addCollect = () => {
    if (likeFlag.value) {
      Message('取消收藏成功', 'success')
    } else {
      store.dispatch('down/pullLike', {
        id: store.state.music.musicId,
        like: true
      })
    }
    likeFlag.value = !likeFlag.value
  }
  // 下载
  const startDown = () => {
    store.dispatch('down/downMusic', store.state.music.musicDetail)
  }

  return {
    startDown,
    addCollect,
    likeFlag,
    gettersMusic,
    scroll,
    playBar,
    playDisc,
    lyricScroll,
    lyric,
    lyricRef,
    lrcObject,
    lyricIndex,
    comBack,
    lyrics,
    isPlay,
    duration,
    songId,
    handleTop,
    commentRef,
    simiRef
  }
}
